package cli

import (
	"blockchaingo/block"
	"blockchaingo/utils"
	"blockchaingo/wallet"
	"fmt"
	"log"
)

//查询余额
func (cli *CLI) getBalance(address string) {
	bc := block.NewBlockChain("test")
	defer block.Close(bc)

	fmt.Printf("Balance of '%s': %d\n", address, cli.getTotalBalance(bc, address))
}

func (cli *CLI) getTotalBalance(bc *block.Blockchain, address string) int {
	if !wallet.ValidateAddress(address) {
		log.Panic("ERROR: Address is not valid")
	}

	balance := 0
	UTXOSet := block.UTXOSet{bc}

	pubKeyHash := utils.Base58Decode([]byte(address))
	pubKeyHash = pubKeyHash[1 : len(pubKeyHash)-4]
	//查询所有未经使用的交易地址
	UTXOs := UTXOSet.FindUTXO(pubKeyHash)
	//算出未使用的交易地址的value和
	for _, out := range UTXOs {
		balance += out.Value
	}
	return balance
}
